import { useMemberStore } from "@/stores"


let baseUrl = `https://pcapi-xiaotuxian-front-devtest.itheima.net`

// 拦截请求配置
const httpInterceptorOptions = {
    // 拦截钱触发
    invoke(options: UniApp.RequestOptions) {
        // 非 http 开头的需要拼接地址
        if (!options.url.startsWith('http')) {
            options.url = baseUrl + options.url
        }

        // 重设超时时间 默认60s 改为60s
        options.timeout = 10000

        // console.log("options", options);

        // 添加请求头表示
        options.header = {
            ...options.header,
            'source-client': 'miniapp'
        }

        // token
        const memberStore = useMemberStore()
        const token = memberStore.profile?.token

        if (token) {
            options.header.Authorization = token
        }
    },
}

uni.addInterceptor("request", httpInterceptorOptions)


interface Data<T> {
    code: string,
    msg: string,
    result: T
}


/**
 * 请求封装
 */
export const http = <T>(options: UniApp.RequestOptions) => {
    return new Promise<Data<T>>((resolve, reject) => {
        uni.request({
            ...options,
            // 请求成功
            success(res) {
                console.log(res);

                if (res.statusCode >= 200 && res.statusCode < 300) {
                    // 获取数据成功，调用 resolve
                    resolve(res.data as Data<T>)
                } else if (res.statusCode == 401) {
                    // 401 错误，调用reject , 没有登录 -> 跳转到登录页
                    const memberStore = useMemberStore()
                    memberStore.clearProfile()
                    // 跳转到登录页
                    uni.navigateTo({url: "/pages/login/login"})
                    reject(res)
                } else {
                    // 通用错误，调用 reject
                    uni.showToast({
                        icon: 'none',
                        title: (res.data as Data<T>).msg || '请求错误'
                    })
                    reject(res)
                }
            },
            // 响应失败
            fail(err) {
                // 网络错误
                uni.showToast({
                    icon: "none",
                    title: "网络错误，换个网络试试"
                })
                reject(err)
            }
        })
    })
}

/**
 * get请求
 */
export const get = <T>(url: string, data?: any) => {
    return http<T>({
        method: "GET",
        url,
        data
    })
}

/**
 * post请求
 */
export const post = <T>(url: string, data: any) => {
    return http<T>({
        method: "POST",
        url,
        data
    })
}